package Project;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.ResultSet;
import java.util.Vector;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

public class StuLogin extends JFrame implements MouseListener {
JFrame jf = new JFrame();
	
	JPanel jp_West;
	JPanel jp_South = new JPanel();
	JPanel jp_Center = new JPanel();
	JPanel jp_sub1 = new JPanel();
	JPanel jp_sub2 = new JPanel();
	
	JLabel lb_totalsub = new JLabel("전체 과목 리스트");
	JLabel lb_mysub = new JLabel("나의 과목 리스트");
	JTextField text;

	DefaultTableModel model1, model2;
	JTable table1, table2;
	JScrollPane spane1, spane2;

	JButton bt_reg, bt_grade, bt_add, bt_del, bt_sel;
	JLabel titlelabel;
	String[] colnames = { "과목번호", "과목이름", "학점", "담당교수" };
	String[] list = { "전체목록", "학생목록", "교수목록" };

	JComboBox listbox;
	String sel = "", sel1 = "";

	boolean addstate = false, delstate = false;
	String stu_num;

	int row, column, row1, column1;

	public StuLogin(Point p, String num) {
		stu_num = num; // 로그인한 학점
		
		jf.setLocation(p);
		jf.setLayout(new BorderLayout());

		bt_reg = new JButton("수강신청");
		bt_grade = new JButton("성적확인");
		bt_add = new JButton("추가");
		bt_del = new JButton("삭제");
		bt_sel = new JButton("선택");

		// titlelabel = new JLabel("학생!", JLabel.CENTER);
		// Font font = new Font("dialog", Font.BOLD, 20);
		// titlelabel.setFont(font);
		// titlelabel.setForeground(new Color(33, 222, 56));

		// text = new JTextField("");

		// 테이블1에 대한 설정------------------------------
		listbox = new JComboBox(list);
		model1 = new DefaultTableModel(null, colnames) {
			// 수정 불가능하게 하기
			public boolean isCellEditable(int i, int c) {
				return false;
			}
		};
		table1 = new JTable(model1);
		spane1 = new JScrollPane(table1);
		table1.addMouseListener(this);
		
		// 테이블2에 대한 설정--------------------------------
		model2 = new DefaultTableModel(null, colnames) {
			public boolean isCellEditable(int i, int c) {
				return false;
			}
		};
		table2 = new JTable(model2);
		spane2 = new JScrollPane(table2);
		table2.addMouseListener(this);

		// ------------------------------ 과목추가-----------------------------
		this.bt_add.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (addstate == true) {
					Vector temp = new Vector();
					temp.add(table1.getValueAt(row, 0).toString());
					temp.add(table1.getValueAt(row, 1).toString());
					temp.add(table1.getValueAt(row, 2).toString());
					temp.add(table1.getValueAt(row, 3).toString());

					DAOTest test = new DAOTest();
					test.OpenDB();
					String sql = "select reg_subnum from regist "
							+ "where reg_stunum=?";

					ResultSet rs;
					Vector vec = new Vector();
					try {
						test.pstmt = test.con.prepareStatement(sql);
						test.pstmt.setString(1, stu_num);
						rs = test.pstmt.executeQuery();
						while (rs.next()) {
							vec.add(rs.getString("reg_subnum"));
						}
					} catch (Exception x) {
						x.printStackTrace();
					}

					// ---------------------------------------------------------
					String sql1 = "insert into regist(reg_stunum, reg_subnum)"
							+ "values(?,?)";
					try {
						int count = model2.getRowCount();
						String num = model1.getValueAt(row, 0).toString();
						System.out.print("num : ");
						System.out.println(num);
						System.out.print("vecnum : ");
						// System.out.println(vec.get(0));
						test.pstmt = test.con.prepareStatement(sql1);
						for (int i = 0; i < vec.size(); i++) {
							if (vec.get(i).equals(num)) {
								return;
							}
						}
						test.pstmt.setString(1, stu_num);
						test.pstmt.setString(2, num);
						int n = test.pstmt.executeUpdate();
						// test.pstmt.setString(2, x)
					} catch (Exception x) {
						x.printStackTrace();
					}
					model2.addRow(temp);
					// -----------------------------------------------------------
				}
			}
		});
		
		// 삭제;
		this.bt_del.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.out.print("row");
				System.out.println(row);
				String temp1 = model2.getValueAt(row1, 0).toString();
				DAOTest test = new DAOTest();
				test.OpenDB();
				System.out.print("row1 : ");
				System.out.println(row1);
				System.out.print("column1 : ");
				System.out.println(column1);
				System.out.print("model2 count : ");

				String sql = "delete from regist " + "where reg_subnum=? "
						+ "and reg_stunum=?";
				try {
					test.pstmt = test.con.prepareStatement(sql);
					test.pstmt.setString(1, temp1);
					test.pstmt.setString(2, stu_num);
					int n = test.pstmt.executeUpdate();
				} catch (Exception x) {
					x.printStackTrace();
				}
				int count = model2.getRowCount();
				for (int i = 0; i < count; i++) {
					if (temp1.equals(model2.getValueAt(i, 0))) {
						model2.removeRow(i);
						return;
					}
				}
				delstate = false;
			}
		});

// 수강 신청 버튼을 눌렀을 경우
		this.bt_reg.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// ----------테이블 로우 모두 삭제-----------
				String[] title = {"과먹번호","과목이름","학점","교수"};
				model1.setColumnIdentifiers(title);
				int count = model1.getRowCount();
				for (int i = 0; i < count; i++) {
					model1.removeRow(0);
				}
				// ------------------------------------------
				DAOTest test = new DAOTest();
				test.OpenDB();
				// 과목번호, 과목이름, 학점, 교수번호를 받아옴
				// 과목테이블의 교수번호와 교수테이블의 교수번호가 일치해야한다.
				String sql = "select sub_num, sub_name, sub_grade, pro_name from subject, professor "
						+ "where subject.sub_num=professor.pro_subnum";
				ResultSet rs;
				try {
					rs = test.stmt.executeQuery(sql);
					while (rs.next()) {
						Vector vec = new Vector();
						vec.add(rs.getString("sub_num"));
						vec.add(rs.getString("sub_name"));
						vec.add(rs.getString("sub_grade"));
						vec.add(rs.getString("pro_name"));
						model1.addRow(vec);
					}
				} catch (Exception x) {}

				int count1 = model2.getRowCount();
				for (int i = 0; i < count1; i++) {
					model2.removeRow(0);
				}
				String sql1 = "select sub_num, sub_name, sub_grade, pro_name from subject, professor "
						+ "where pro_num in(select pro_num from professor where pro_subnum in"
						+ "(select reg_subnum from regist where reg_stunum=?))"
						+ "and subject.sub_num=professor.pro_subnum";
				try {
					test.pstmt = test.con.prepareStatement(sql1);
					test.pstmt.setString(1, stu_num);
					System.out.print("stu_num");
					System.out.println(stu_num);
					test.pstmt.executeQuery();
					rs = test.pstmt.executeQuery();
					while (rs.next()) {
						System.out.println("while문 수행");
						Vector vec = new Vector();
						vec.add(rs.getString("sub_num"));
						vec.add(rs.getString("sub_name"));
						vec.add(rs.getString("sub_grade"));
						vec.add(rs.getString("pro_name"));
						model2.addRow(vec);
					}
				} catch (Exception x) {x.printStackTrace();}
				// ///////////////////////////////////////////
				jp_South.setLayout(new FlowLayout());
				jp_South.add(bt_add);
				jp_South.add(bt_del);

				jp_Center.remove(spane1);

				// Table UI
				jp_Center.setLayout(new GridLayout(2, 1));
				jp_sub1.setLayout(new BoxLayout(jp_sub1, BoxLayout.Y_AXIS));
				jp_sub2.setLayout(new BoxLayout(jp_sub2, BoxLayout.Y_AXIS));
				
				jp_sub1.add(lb_totalsub);
				jp_sub1.add(spane1);
				
				jp_sub2.add(lb_mysub);
				jp_sub2.add(spane2);
				jp_Center.add(jp_sub1); // 상단 테이블
				jp_Center.add(jp_sub2);
				table1.setPreferredScrollableViewportSize(new Dimension(450,
						100));

				jf.add(jp_Center, "Center");
				jf.add(jp_South, "South");
				jf.validate();
				// ////////////////////////////////////////////

				table1.getTableHeader().getColumnModel().getColumn(3)
						.setHeaderValue("교수");
			}
		});
		
// ---------------- 성적확인--------------------
		this.bt_grade.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//--------------점수열 추가--------------
				int colcount = model1.getColumnCount();
				if(colcount<5)
					model1.addColumn("점수");
				//---------------------------------------
				//---------------모든행 삭제--------------
				int count = model1.getRowCount();
				for (int i = 0; i < count; i++) {
					model1.removeRow(0);
				}
				//-----------------------------------------
				DAOTest test = new DAOTest();
				test.OpenDB();
				// 해당 학생의 수강신청 과목 리스트와 점수를 불러온다.
				String sql1 = "select sub_num, sub_name, sub_grade, pro_name, grade from subject, professor, regist "
						+ "where pro_num in(select pro_num from professor where pro_subnum in"
						+ "(select reg_subnum from regist where reg_stunum=?))"
						+ "and subject.sub_num=professor.pro_subnum "
						+ "and subject.sub_num=regist.reg_subnum";
				ResultSet rs;
				try {
					test.pstmt = test.con.prepareStatement(sql1);
					test.pstmt.setString(1, stu_num);
					rs = test.pstmt.executeQuery();
					while (rs.next()) {
						System.out.println("while문 수행");
						Vector vec = new Vector();
						vec.add(rs.getString("sub_num"));
						vec.add(rs.getString("sub_name"));
						vec.add(rs.getString("sub_grade"));
						vec.add(rs.getString("pro_name"));
						vec.add(rs.getString("grade"));
						model1.addRow(vec);
					}
				} catch (Exception x) {x.printStackTrace();}
				// //////////////////////////////////////////
				
				jp_South.setLayout(new BorderLayout());

				jp_Center.remove(jp_sub1);
				jp_Center.remove(jp_sub2);
				
				jp_Center.setLayout(new BorderLayout());

				jp_Center.add(spane1); // 상단 테이블

				table1.setPreferredScrollableViewportSize(new Dimension(450,
						400));

				jf.add(jp_Center, "Center");
				jf.add(jp_South, "South");
				jf.validate();
				// //////////////////////////////////////////
			}
		});
	}

	public void stulogbutton() {
		// West UI
		DAOTest test = new DAOTest();
		test.OpenDB();
		String sql = "select pro_name from professor where pro_num=" +
				"(select stu_pronum from student where stu_num=?)";
		ResultSet rs;
		String str="";
		try{
			test.pstmt = test.con.prepareStatement(sql);
			test.pstmt.setString(1, stu_num);
			rs = test.pstmt.executeQuery();
			while(rs.next()){
				str = rs.getString("pro_name").toString();
			}
		}catch(Exception x){
			x.printStackTrace();
		}
		
		this.jp_West = new JPanel();
		jp_West.setLayout(new GridLayout(6, 1));
		jp_West.add(new JLabel(""));
		jp_West.add(this.bt_reg); // 수강신청 버튼 추가
		jp_West.add(new JLabel(""));
		jp_West.add(this.bt_grade); // 성적확인 버튼 추가
		jp_West.add(new JLabel(""));

		JPanel jp = new JPanel();
		JButton bt = new JButton("로그아웃");
		bt.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				Point p = jf.getLocation();
				jf.setVisible(false);
				LoginUi ui = new LoginUi();
				ui.LoginUI(p);
				ui.uiframe();
			}
		});
		jp.add(new JLabel("지도교수 : " + str));
		jp.add(bt);
		
		jf.add(jp, "North");
		jf.add(this.jp_West, "West");
		jf.validate();
		
		
		jf.setPreferredSize(new Dimension(600, 400));
		jf.pack();
		jf.setDefaultCloseOperation(EXIT_ON_CLOSE);
		jf.setVisible(true);
	}

	public void mouseClicked(MouseEvent me) {
		if (me.getSource() == table1) {
			System.out.println("나의 테이블 선택");
			row = table1.getSelectedRow();
			this.column = table1.getSelectedRow();
			this.sel = table1.getValueAt(row, 0).toString();
			addstate = true;
		}
		if (me.getSource() == table2) {
			row1 = table2.getSelectedRow();
			column1 = table2.getSelectedColumn();
			System.out.println(model2.getValueAt(row1, 0));
		}
	}
	public void mouseEntered(MouseEvent e) {}
	public void mouseExited(MouseEvent e) {}
	public void mousePressed(MouseEvent e) {}
	public void mouseReleased(MouseEvent e) {}

}
